<template>
  <div>
    <div class="btns">
      <el-button @click="reflashData">更新数据</el-button>
    </div>
    <div ref="showAgTable" v-size-ob="whenRisizeChange">
      <ag-grid-vue
        class="ag-theme-quartz"
        :style="`width: 100%; height: ${boxHeight}px;`"
        :defaultColDef="defaultColDef"
        :columnTypes="columnTypes"
        :columnDefs="columnDefs"
        :headerHeight="headerHeight"
        :rowHeight="rowHeight"
        rowSelection="single"
        :getRowId="(params) => params.data.mySelfId"
        @grid-ready="onGridReady"
      >
      </ag-grid-vue>
    </div>
  </div>
</template>
<script>
import { AgGridVue } from "ag-grid-vue";
import { nanoid } from "nanoid";

export default {
  data() {
    return {
      boxHeight: 300,
      tableData: [],
    };
  },
  components: {
    AgGridVue,
  },
  created() {
    this.headerHeight = 32;
    this.rowHeight = 32;
    //默认配置
    this.defaultColDef = {
      suppressMovable: true, //可以移动列
      sortable: true,
      //是否可以调整列大小，就是拖动改变列大小
      resizable: true,
      //开启刷选
      filter: true,
      flex: 1,
    };
    //定义列类型
    this.columnTypes = {};
    this.columnDefs = [
      {
        field: "make",
        headerName: "姓名",
        pinned: "left",
        initialSort: "asc",
        initialPinned: "left",
        headerClass: "country-header",
      },
      { field: "model", headerName: "性别" },
      { field: "price", headerName: "价格" },
    ];
    this.tableData = [
      { make: "Toyota", model: "Celica", price: 35000, mySelfId: 1 },
      { make: "Ford", model: "Mondeo", price: 32000, mySelfId: 2 },
      { make: "Porsche", model: "Boxster", price: 72000, mySelfId: 3 },
    ];
    for (let i = 0; i < 100; i++) {
      this.tableData.push({
        make: `x${i}x`,
        model: `${i}Mondeo`,
        price: Math.random() * 10,
        mySelfId: nanoid(),
      });
    }
  },
  methods: {
    reflashData() {},
    changeColumns() {
      const columnDefs = this.getColumnDefs();
      this.gridApi.setGridOption("columnDefs", colDefsMedalsExcluded);
    },
    onGridReady(params) {
      this.gridApi = params.api;
      this.gridColumnApi = params.columnApi;
      this.getData();
    },
    getData() {
      this.gridApi.showLoadingOverlay();
      this.gridApi.hideOverlay();
      this.gridApi.setRowData(this.tableData);
    },
    whenRisizeChange() {
      this.$nextTick(() => {
        // this.gridApi.sizeColumnsToFit();
        this.boxHeight =
          document.documentElement.clientHeight -
          this.$refs.showAgTable.getBoundingClientRect().top -
          15;
      });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .blue-color {
  color: blue;
}
</style>
